package info.batcloud.fanli.core.service.impl;

import com.taobao.api.TaobaoClient;
import info.batcloud.fanli.core.constants.TaobaoClientConstants;
import info.batcloud.fanli.core.dto.TaobaoOauthDTO;
import info.batcloud.fanli.core.entity.TaobaoOauth;
import info.batcloud.fanli.core.repository.TaobaoAccountRepository;
import info.batcloud.fanli.core.repository.TaobaoOauthRepository;
import info.batcloud.fanli.core.service.TaobaoOauthService;
import info.batcloud.fanli.core.service.TbkPrivateService;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.inject.Inject;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class TaobaoOauthServiceImpl implements TaobaoOauthService {

    @Inject
    private TaobaoOauthRepository taobaoOauthRepository;

    @Inject
    private TaobaoAccountRepository taobaoAccountRepository;

    @Inject
    @Qualifier(TaobaoClientConstants.TAOBAO_CLIENT_ITEM_TBK)
    private TaobaoClient taobaoClient;

    @Inject
    private TbkPrivateService tbkPrivateService;


    @Override
    public String findAccessTokenByUserIdAndTaobaoUserId(long userId, String taobaoUserId) {
        return taobaoOauthRepository.findByUserIdAndTaobaoUserId(userId, taobaoUserId).getAccessToken();
    }

    @Override
    public List<TaobaoOauthDTO> findByUserId(long userId) {
        List<TaobaoOauth> oauths = taobaoOauthRepository.findByUserId(userId);
        List<TaobaoOauthDTO> infoList = new ArrayList<>();
        for (TaobaoOauth oauth : oauths) {
            TaobaoOauthDTO info = new TaobaoOauthDTO();
            info.setExpired(oauth.getExpiration().before(new Date()));
            info.setTaobaoUserId(oauth.getTaobaoUserId());
            info.setTaobaoUserNick(oauth.getTaobaoUserNick());
            infoList.add(info);
        }
        return infoList;
    }

}
